# GameManager.gd - 游戏管理器
# 《光影之间》- 全局游戏流程管理

extends Node

# 游戏状态枚举
enum GameMode {
	MENU,
	PLAYING,
	PAUSED,
	LOADING,
	GAME_OVER
}

# 当前游戏状态
var current_mode := GameMode.MENU
var current_scene: Node = null
var loading_progress := 0.0

# 场景路径
var scene_paths := {
	"main_menu": "res://scenes/ui/MainMenu.tscn",
	"chapter1_level1": "res://scenes/levels/Chapter1_Level1.tscn",
	"chapter1_level2": "res://scenes/levels/Chapter1_Level2.tscn",
	"settings": "res://scenes/ui/SettingsMenu.tscn",
	"credits": "res://scenes/ui/Credits.tscn"
}

# 当前关卡信息
var current_chapter := 1
var current_level := 1

# 信号
signal scene_changed(scene_name: String)
signal game_mode_changed(new_mode: GameMode)
signal loading_progress_updated(progress: float)
signal level_completed(chapter: int, level: int)

func _ready():
	print("游戏管理器已初始化")
	set_game_mode(GameMode.MENU)
	
	# 连接场景树信号
	get_tree().node_added.connect(_on_node_added)

func _input(event):
	# 处理全局输入
	if event.is_action_pressed("pause"):
		toggle_pause()

# 设置游戏模式
func set_game_mode(new_mode: GameMode):
	if current_mode != new_mode:
		var old_mode = current_mode
		current_mode = new_mode
		game_mode_changed.emit(new_mode)
		print("游戏模式变更: ", GameMode.keys()[old_mode], " -> ", GameMode.keys()[new_mode])

# 切换场景
func change_scene(scene_name: String):
	if not scene_paths.has(scene_name):
		print("错误: 未找到场景 ", scene_name)
		return false
	
	set_game_mode(GameMode.LOADING)
	
	var scene_path = scene_paths[scene_name]
	print("正在加载场景: ", scene_path)
	
	# 异步加载场景
	var loader = ResourceLoader.load_threaded_request(scene_path)
	if loader == null:
		print("错误: 无法开始加载场景 ", scene_path)
		return false
	
	# 等待加载完成
	await load_scene_async(scene_path)
	
	# 切换到新场景
	var new_scene = ResourceLoader.load_threaded_get(scene_path)
	if new_scene:
		get_tree().change_scene_to_packed(new_scene)
		current_scene = get_tree().current_scene
		scene_changed.emit(scene_name)
		set_game_mode(GameMode.PLAYING)
		print("场景切换完成: ", scene_name)
		return true
	else:
		print("错误: 场景加载失败 ", scene_path)
		set_game_mode(GameMode.MENU)
		return false

# 异步加载场景
func load_scene_async(scene_path: String):
	while true:
		var status = ResourceLoader.load_threaded_get_status(scene_path)
		match status:
			ResourceLoader.THREAD_LOAD_INVALID_RESOURCE:
				print("错误: 无效的资源路径")
				return
			ResourceLoader.THREAD_LOAD_IN_PROGRESS:
				loading_progress = ResourceLoader.load_threaded_get_status(scene_path, [])
				loading_progress_updated.emit(loading_progress)
				await get_tree().process_frame
			ResourceLoader.THREAD_LOAD_FAILED:
				print("错误: 场景加载失败")
				return
			ResourceLoader.THREAD_LOAD_LOADED:
				loading_progress = 1.0
				loading_progress_updated.emit(loading_progress)
				return

# 开始新游戏
func start_new_game():
	print("开始新游戏")
	
	# 重置游戏状态
	if GameState:
		GameState.start_new_game()
	
	# 加载第一章第一关
	current_chapter = 1
	current_level = 1
	change_scene("chapter1_level1")

# 继续游戏
func continue_game():
	print("继续游戏")
	
	# 加载保存的进度
	if GameState:
		var save_data = GameState.load_game()
		if save_data:
			current_chapter = save_data.get("current_chapter", 1)
			current_level = save_data.get("current_level", 1)
			
			var scene_name = "chapter%d_level%d" % [current_chapter, current_level]
			change_scene(scene_name)
		else:
			print("没有找到存档，开始新游戏")
			start_new_game()

# 完成关卡
func complete_level(chapter: int, level: int):
	print("关卡完成: 第", chapter, "章 第", level, "关")
	
	level_completed.emit(chapter, level)
	
	# 更新当前关卡
	current_chapter = chapter
	current_level = level
	
	# 保存进度
	if GameState:
		var level_number = chapter * 10 + level  # 将章节和关卡转换为唯一的关卡编号
		var completion_data = {
			"chapter": chapter,
			"level": level,
			"completed_time": Time.get_unix_time_from_system(),
			"score": 100  # 默认分数
		}
		GameState.complete_level(level_number, completion_data)
		GameState.save_game()
	
	# 加载下一关
	load_next_level()

# 加载下一关
func load_next_level():
	var next_level = current_level + 1
	var next_scene_name = "chapter%d_level%d" % [current_chapter, next_level]
	
	if scene_paths.has(next_scene_name):
		current_level = next_level
		change_scene(next_scene_name)
	else:
		# 检查是否有下一章
		var next_chapter = current_chapter + 1
		var next_chapter_scene = "chapter%d_level1" % next_chapter
		
		if scene_paths.has(next_chapter_scene):
			current_chapter = next_chapter
			current_level = 1
			change_scene(next_chapter_scene)
		else:
			# 游戏完成
			print("游戏完成！")
			show_game_complete()

# 显示游戏完成界面
func show_game_complete():
	# 这里可以加载游戏完成场景
	print("显示游戏完成界面")
	change_scene("credits")

# 暂停/恢复游戏
func toggle_pause():
	if current_mode == GameMode.PLAYING:
		set_game_mode(GameMode.PAUSED)
		get_tree().paused = true
		print("游戏暂停")
	elif current_mode == GameMode.PAUSED:
		set_game_mode(GameMode.PLAYING)
		get_tree().paused = false
		print("游戏恢复")

# 退出到主菜单
func return_to_main_menu():
	print("返回主菜单")
	
	# 保存当前进度
	if GameState:
		GameState.save_game()
	
	# 恢复游戏状态
	get_tree().paused = false
	
	# 切换到主菜单
	change_scene("main_menu")

# 退出游戏
func quit_game():
	print("退出游戏")
	
	# 保存游戏数据
	if GameState:
		GameState.save_game()
	
	# 退出应用
	get_tree().quit()

# 重启当前关卡
func restart_current_level():
	print("重启当前关卡")
	
	var scene_name = "chapter%d_level%d" % [current_chapter, current_level]
	change_scene(scene_name)

# 节点添加事件
func _on_node_added(node: Node):
	# 如果是关卡场景，连接相关信号
	if node.has_signal("level_completed_signal"):
		node.level_completed_signal.connect(_on_level_completed)

# 关卡完成事件
func _on_level_completed():
	complete_level(current_chapter, current_level)

# 获取当前关卡信息
func get_current_level_info() -> Dictionary:
	return {
		"chapter": current_chapter,
		"level": current_level,
		"mode": current_mode
	}

# 设置当前关卡
func set_current_level(chapter: int, level: int):
	current_chapter = chapter
	current_level = level

# 检查场景是否存在
func scene_exists(scene_name: String) -> bool:
	return scene_paths.has(scene_name)

# 添加场景路径
func add_scene_path(scene_name: String, path: String):
	scene_paths[scene_name] = path
	print("添加场景路径: ", scene_name, " -> ", path)

# 获取加载进度
func get_loading_progress() -> float:
	return loading_progress

# 处理影视能力状态变化
func on_shadow_vision_changed(is_active: bool):
	# 通知光照系统
	if LightingSystem:
		LightingSystem.toggle_shadow_vision(is_active)
	
	# 这里可以添加其他需要响应影视状态变化的逻辑
	print("影视能力状态变化: ", is_active)
